package edu.chl.food_store.beans.ejb;

import edu.chl.food_store.entities.Customer;
import javax.ejb.Stateless;
import javax.persistence.*;

/**
 * CustomerEJB:
 * Handles user operations on the database (registration/validation).
 */
@Stateless
public class CustomerEJB {

    @PersistenceContext(unitName = "foodstore_pu")
    private EntityManager em;

    /**
     * Finds a specific customer by e-mail.
     */
    public Customer findCustomerByEmail(String email) {
        Customer customer;
        Query query = em.createNamedQuery("findCustomerByEmail");
        query.setParameter("custEmail", email);
        try {
            customer = (Customer) query.getSingleResult();
        } catch (Exception ex) {
            customer = null;
        }
        return customer;
    }

    /**
     * Creates a customer and persists it. Returns true if the customer was 
     * persisted sucessfully, otherwise false.
     */
    public boolean createCustomer(Customer customer) {
        try {
            em.persist(customer);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Validates a customer using given email and password.
     */
    public Customer validateCustomer(String email, String password) {
        //Check if the customer exists in the database
        Query query = em.createNamedQuery("findCustomerByEmail");
        query.setParameter("custEmail", email);
        Customer customer;
        try {
            customer = (Customer) query.getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
        //If not return false
        if (customer != null && customer.getPass().equals(password)) {
            return customer;
        } else {
            return null;
        }
    }
}
